//
//  JXTabBarController.m
//  JiaoX
//
//  Created by jiaoxiu－004 on 14-10-11.
//  Copyright (c) 2014年 北京娇羞科技有限公司. All rights reserved.
//

#import "JXTabBarController.h"
#import "JXOldHomeController.h"
#import "JXHomeController.h"
#import "JXCartController.h"
#import "JXMineController.h"
#import "JXCategory2Controller.h"

#import "JXForumController.h"
#import "JXAppInfo.h"
#import "NavigationItem.h"
#import "CartInfoDao.h"
#import "JXLoginRegistCheckController.h"
#import "JXChatManager.h"
#import "EmotionUtil.h"
@interface JXTabBarController ()<UITabBarControllerDelegate>
{
    CartInfoDao *_cartInfoDao;
    
}
@property (nonatomic, weak) UIViewController *lastSelectedViewContoller;
@property (nonatomic, weak) JXCartController *cart;
@property (nonatomic, weak) JXForumController *forum;
@property (nonatomic, weak) JXCategory2Controller *category;

@end

@implementation JXTabBarController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setDelegate:self];
    
    [[JXChatManager sharedInstance] getSignAndOpenSession];
    
    _cartInfoDao = [[CartInfoDao alloc]init];
    
    //添加各个controller
    JXHomeController *home = [[JXHomeController alloc]init];
    [self addOneChlildVc:home title:@"首页" imageName:@"tabbar_home" selectedImageName:@"tabbar_home_selected"];
    
    //分类
    JXCategory2Controller *category = [[JXCategory2Controller alloc]init];
    [self addOneChlildVc:category title:@"分类" imageName:@"tabbar_category" selectedImageName:@"tabbar_category_selected"];
    _category = category;
    if ([Utils isHaveNetWorking] && [UserDefaultsHelper boolForKey:KEY_SHOW_FORUM]) {
        //论坛
        JXForumController *forum = [[JXForumController alloc]init];
        [self addOneChlildVc:forum title:@"论坛" imageName:@"tabbar_bbs" selectedImageName:@"tabbar_bbs_selected"];
        _forum = forum;
    }
    //购物车
    JXCartController *cart = [[JXCartController alloc]init];
    [self addOneChlildVc:cart title:@"购物车" imageName:@"tabbar_cart" selectedImageName:@"tabbar_cart_selected"];
    _cart = cart;
    //个人中心
    JXMineController *mine = [[JXMineController alloc]init];
    [self addOneChlildVc:mine title:@"我" imageName:@"tabbar_self" selectedImageName:@"tabbar_self_selected"];
   
    //注册身份过期的通知
    [[NSNotificationCenter defaultCenter] addObserver: self selector:@selector(callBack)name:@"token_timeout" object:nil];
    //注册跳转到购物车通知
    [[NSNotificationCenter defaultCenter] addObserver: self selector:@selector(toCartCtrl)name:@"to_cartctrl" object:nil];
    //注册跳转论坛通知
    [[NSNotificationCenter defaultCenter] addObserver: self selector:@selector(toForumCtrl)name:@"to_forum" object:nil];
    //注册更新所有badgevalue的通知
    [[NSNotificationCenter defaultCenter] addObserver: self selector:@selector(getUnreadCount) name:NOTI_UPDATA_BADGE_NUM object:nil];
}

-(void)callBack{
    //身份过期
    [Utils clearUserInfo];
    JXNavigationController *nav = [[JXNavigationController alloc]initWithRootViewController:[[JXLoginRegistCheckController alloc]init]];
    [self presentViewController:nav animated:true completion:^{}];
    [self.viewControllers makeObjectsPerformSelector:@selector(popToRootViewControllerAnimated:) withObject:[NSNumber numberWithBool:YES]];
}

/**
 *  去购物车
 */
-(void)toCartCtrl{
    [self setSelectedClass:[JXCartController class]];
    [self.viewControllers makeObjectsPerformSelector:@selector(popToRootViewControllerAnimated:) withObject:[NSNumber numberWithBool:YES]];
}

/**
 *  去论坛
 */
-(void)toForumCtrl{
    if (_forum) {
        [self setSelectedClass:[JXForumController class]];
        [self.viewControllers makeObjectsPerformSelector:@selector(popToRootViewControllerAnimated:) withObject:[NSNumber numberWithBool:YES]];
    }
}

-(void)setSelectedClass:(Class)class{
    for (UINavigationController *ctrl in self.viewControllers) {
        if ([[ctrl.viewControllers firstObject] isKindOfClass:class]) {
            NSUInteger index = [self.viewControllers indexOfObject:ctrl];
            [self setSelectedIndex:index];
            break;
        }
    }
}

-(void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UINavigationController *)viewController{
    UIViewController *vc = [viewController.viewControllers firstObject];
    if ([vc isKindOfClass:[JXCategory2Controller class]]) {
        if (self.lastSelectedViewContoller == vc) {
            
        }
    }
    
    self.lastSelectedViewContoller = vc;
}

/**
 *  修改购物车count
 */
- (void)getUnreadCount
{
    // 1.获取购物车商品数
    NSInteger prodNum = [_cartInfoDao queryProdsCount];
    // 显示购物车
    _cart.tabBarItem.badgeValue = prodNum == 0?0:[NSString stringWithFormat:@"%ld", (long)prodNum];
    
    // 2.1 获取聊天未读条数
    NSInteger msgUnreadCount = [[JXChatManager sharedInstance].chatMsgDao getAllUnReadMsgCount];
    NSInteger minePostsUnreadCount = [UserDefaultsHelper integerForKey:KEY_MYPOSTS_NOTI_NUM];
    NSInteger readMineUnreadCount = [UserDefaultsHelper integerForKey:KEY_REPLY_MINE_COMT_NOTI_NUM]+[UserDefaultsHelper integerForKey:KEY_REPLY_MINE_POST_NOTI_NUM];
    NSInteger total = msgUnreadCount+minePostsUnreadCount+readMineUnreadCount;
    _forum.tabBarItem.badgeValue = total==0?0:[NSString stringWithFormat:@"%ld", (long)total];
    
    // 在图标上显示所有的未读数
    [UIApplication sharedApplication].applicationIconBadgeNumber = prodNum;
    
}

/**
 *  添加一个子控制器
 *
 *  @param childVc           子控制器对象
 *  @param title             标题
 *  @param imageName         图标
 *  @param selectedImageName 选中的图标
 */
- (void)addOneChlildVc:(UIViewController *)childVc title:(NSString *)title imageName:(NSString *)imageName selectedImageName:(NSString *)selectedImageName
{
    // 设置标题
    // 相当于同时设置了tabBarItem.title和navigationItem.title
    childVc.title = title;
    
    // 设置图标
    childVc.tabBarItem.image = [UIImage imageNamed:imageName];
    
    // 设置选中的图标
    UIImage *selectedImage = [UIImage imageNamed:selectedImageName];
        // 声明这张图片用原图(别渲染)
    selectedImage = [selectedImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    childVc.tabBarItem.selectedImage = selectedImage;
    [childVc.tabBarItem setFinishedSelectedImage:selectedImage withFinishedUnselectedImage:[UIImage imageNamed:imageName]];
    // 设置tabBarItem的普通文字颜色
    NSMutableDictionary *textAttrs = [NSMutableDictionary dictionary];
    textAttrs[NSForegroundColorAttributeName] = [UIColor blackColor];
    textAttrs[NSFontAttributeName] = [UIFont systemFontOfSize:10];
    [childVc.tabBarItem setTitleTextAttributes:textAttrs forState:UIControlStateNormal];
    
    // 设置tabBarItem的选中文字颜色
    NSMutableDictionary *selectedTextAttrs = [NSMutableDictionary dictionary];
    selectedTextAttrs[NSForegroundColorAttributeName] = JXThemeColor;
    [childVc.tabBarItem setTitleTextAttributes:selectedTextAttrs forState:UIControlStateSelected];
    
    // 添加为tabbar控制器的子控制器
    UINavigationController *nav = [[JXNavigationController alloc] initWithRootViewController:childVc];
    [self addChildViewController:nav];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}


- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"token_timeout" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NOTI_UPDATA_BADGE_NUM object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"to_cartctrl" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"to_forum" object:nil];
}

@end
